package com.example.demobetwixt;

import org.apache.commons.betwixt.io.BeanReader;
import org.apache.commons.betwixt.io.BeanWriter;
import org.apache.xmlbeans.XmlException;

import java.io.*;

/**
 * @author lzh
 * @date 2019/11/13 - 14:19
 */
public class TestBetwixt {

    public static Object fromXml(InputStream in, Class clazz)
            throws XmlException {

        BeanReader beanReader = new BeanReader();
        Object object = null;
        try {
            beanReader.registerBeanClass(clazz);
            beanReader.getXMLIntrospector().setWrapCollectionsInElement(true);
            object = beanReader.parse(in);
        } catch (Exception e) {
            throw new XmlException(e);
        }
        return object;
    }


    public static Class parseFromXml(String path) throws Exception {

        FileInputStream in;
        Class obj = null;
        try {
            in = new FileInputStream(path);
            obj = (Class) TestBetwixt.fromXml(in, Class.class);
        } catch (FileNotFoundException e) {
            throw new Exception(e);
        } catch (Exception e) {
            throw new Exception(e);
        }

        return obj;
    }


    public static void toXml(Object object, OutputStream out)
            throws Exception {
        try {
            BeanWriter beanWriter = new BeanWriter(out, "UTF-8");
            beanWriter.enablePrettyPrint();
            beanWriter.setIndent("    ");
            beanWriter.setEndOfLine(System.getProperty("line.separator"));
            beanWriter.writeXmlDeclaration("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            beanWriter.getXMLIntrospector().setWrapCollectionsInElement(true);
            beanWriter.setWriteEmptyElements(false);
            beanWriter.write(object);
            beanWriter.close();
        } catch (Exception e) {
            throw new XmlException(e);
        }
    }


    public static void writeToXml(Object object, String path)
            throws Exception {

        try {
            FileOutputStream out = new FileOutputStream(path);
            TestBetwixt.toXml(object, out);
            out.close();
        } catch (FileNotFoundException e) {
            throw new Exception(e);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        try {
            writeToXml(new TestObj("qerq",12) , "D:\\qwert.xml");
        } catch (Exception e) {
            e.printStackTrace();
        }





    }





}
